# -*- coding: UTF-8 -*-     
import tornado.ioloop
import tornado.web
import requests
import json 
import random
from pyquery import PyQuery as pq

config = {
    'master': {
        'avatar': 'http://case.tiesec.org/assistant/public/img/master.jpg'
    },
    'robot': {
        'avatar': 'http://case.tiesec.org/assistant/public/img/robot.jpg'
    }
}

dialog_format = [{
    'direction': 'left',
    'type': 'text',
    'content': '',
    'avatar': config['robot']['avatar']
}]

request_url = "https://zhidao.baidu.com/search?lm=0&rn=10&pn=0&fr=search&word="
request_headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
    'Upgrade-Insecure-Requests' : '1',
    'Pragma' : 'no-cache',
    'Cache-Control' : 'no-cache',
    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
}

class CrossDomain:
    def __init__(self):
        pass

    def write(self, str):
        self.set_header("Content-Type","application/json")
        self.set_header("Access-Control-Allow-Origin","*")
        self.set_header("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS")
        self.set_header("Access-Control-Allow-Headers","Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
        self.write(str)

class MainHandler(tornado.web.RequestHandler, CrossDomain):
    def get(self):
        CrossDomain.write(self, r'hey man!')

class CharHandler(tornado.web.RequestHandler, CrossDomain):
    def get(self):
        CrossDomain.write(self, r'hey man!')

    def options(self):
        CrossDomain.write(self, '')

    def post(self):
        post_obj = tornado.escape.json_decode(self.request.body)
        post_content_data = ''
        if ( 'content' in post_obj ): 
            post_content_data = post_obj['content'] 
        r = requests.get(url=request_url+post_content_data, headers=request_headers)
        r.encoding='gbk'
        html = r.text
        q = pq(html)
        answer = q(".dd.answer").eq(random.randint(0,9)).text().replace("答： ", "").replace("案: ", "")
        dialog_format[0]['content'] = answer
        CrossDomain.write(self, json.dumps(dialog_format))

class GetInfoHandler(tornado.web.RequestHandler, CrossDomain):
    def get(self):
        CrossDomain.write(self, json.dumps(config['master']))

    def options(self):
        CrossDomain.write(self, json.dumps(config['master']))

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
        (r"/Chat", CharHandler),
        (r"/getMaster", GetInfoHandler)
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(3000)
    tornado.ioloop.IOLoop.current().start()